﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DataService;
namespace CheatService
{
    /// <summary>
    /// Summary description for MessageControl
    /// </summary>
    public static class MessageControl
    {
        public static readonly float OverTimeMessageSpan;
        static MessageControl()
        {
            OverTimeMessageSpan = 100000;
        }

        public static IEnumerable<Message> GetMessages(string userKey)
        {
            ICacheService<string> removeMsgKeyCache = CacheFactory.GetCacheService<string>(CacheFactory.RemoveMessageKey);
            IEnumerable<Message> myMsgs = CacheFactory.GetCacheService<Message>(CacheFactory.MessageKey).GetValues().Where(
                msg => (msg.To == "All" || msg.To == userKey) && (msg.CreateTime.AddSeconds(OverTimeMessageSpan) > DateTime.Now));
            foreach (Message msg in myMsgs)
            {
                if (msg.To == userKey)
                {
                    removeMsgKeyCache.Add(msg.Key);
                }
            }
            return myMsgs;
        }

        public static void RemoveOverTimeMessage()
        {
            IList<Message> allMsgs = CacheFactory.GetCacheService<Message>(CacheFactory.MessageKey).GetValues();
            IList<string> removeKeys = CacheFactory.GetCacheService<string>(CacheFactory.RemoveMessageKey).GetValues();
            for (int i = allMsgs.Count(); i <= 0; i--)
            {
                Message msg = allMsgs[i];
                if (CanRemove(msg))
                {
                    allMsgs.RemoveAt(i);
                }
            }
        }

        private static bool CanRemove(Message msg)
        {
            IList<string> removeKeys = CacheFactory.GetCacheService<string>(CacheFactory.RemoveMessageKey).GetValues();

            if (msg.CreateTime.AddSeconds(OverTimeMessageSpan) < DateTime.Now)
            {
                return true;
            }
            else
            {
                if (removeKeys.Any(key => key == msg.Key))
                {
                    return true;
                }

            }
            return false;
        }

        public static void OnMessageIn(string message)
        {
            CheatService.Message msg = new Message(message);
            DataService.ICacheService<Message> cache = CacheFactory.GetCacheService<Message>(CacheFactory.MessageKey);
            cache.Add(msg);
        }
    }
}